﻿using LeanApp.Bll;
using LeanApp.Common;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace LeanApp.View
{
    /// <summary>
    /// LineBalanceCtrl.xaml 的交互逻辑
    /// </summary>
    public partial class LineBalanceCtrl : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public LineBalanceCtrl()
        {
            InitializeComponent();
            BindEvent();
            RefreshLineName();
        }

        /// <summary>
        /// 绑定事件
        /// </summary>
        private void BindEvent()
        {
            btnAddLine.Click += BtnAddLine_Click;
            cmbLine.SelectionChanged += CmbLine_SelectionChanged;
            btnAddVersion.Click += BtnAddVersion_Click;
            cmbVersion.SelectionChanged += CmbVersion_SelectionChanged;
            btnAddWorkStation.Click += BtnAddWorkStation_Click;
            cmbWorkStation.SelectionChanged += CmbWorkStation_SelectionChanged;
            btnAddMachine.Click += BtnAddMachine_Click;
            cmbMachine.SelectionChanged += CmbMachine_SelectionChanged;
            cmbTimeUnit.SelectionChanged += CmbTimeUnit_SelectionChanged;
            btnSaveRecord.Click += BtnSaveRecord_Click;
            btnStartAnalysis.Click += BtnStartAnalysis_Click;
            btnImportFromFile.Click += BtnImportFromFile_Click;
        }

        /// <summary>
        /// 从文件导入数据到数据库
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void BtnImportFromFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "请打开要导入数据的文件";
                openFileDialog.Filter = "Excel文件|*.xlsx|Excel文件|*.xls";
                if (openFileDialog.ShowDialog() == true)
                {
                    string fileName = openFileDialog.FileName;
                    List<Dictionary<string, object>> fileData = ExcelTool.ReadExcel(fileName);
                    if (fileData.Count <= 0 || fileData[0] == null || fileData[0].Count <= 0)
                    {
                        MessageBox.Show("数据读取失败");
                    }
                    else
                    {
                        if (_bll.ImportData(fileData))
                        {
                            RefreshLineName();
                        }
                        else
                        {
                            MessageBox.Show("数据导入失败");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 开始分析单击事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void BtnStartAnalysis_Click(object sender, RoutedEventArgs e)
        {
            txtLineBalanceValue.Text = _bll.LineBalanceResult;
            txtLineBalanceTag.Visibility = Visibility.Visible;
            txtLineBalanceValue.Visibility = Visibility.Visible;

            BalanceChartCtrl balanceCtrl = new BalanceChartCtrl("线平衡分析", _bll);
            if (lineBalanceResultContainer.Children.Count > 0)
            {
                lineBalanceResultContainer.Children.Clear();
            }
            lineBalanceResultContainer.Children.Add(balanceCtrl);
            BalanceEquipmentChartCtrl equipmentCtrl = new BalanceEquipmentChartCtrl("设备负荷均衡分析", _bll);
            if (lineBalanceEquipmentResultContainer.Children.Count > 0)
            {
                lineBalanceEquipmentResultContainer.Children.Clear();
            }
            lineBalanceEquipmentResultContainer.Children.Add(equipmentCtrl);
            BalanceEquipmentDiffChartCtrl equipmentDiffCtrl = new BalanceEquipmentDiffChartCtrl("设备负荷差异分析", _bll);
            if (lineBalanceEquipmentDiffResultContainer.Children.Count > 0)
            {
                lineBalanceEquipmentDiffResultContainer.Children.Clear();
            }
            lineBalanceEquipmentDiffResultContainer.Children.Add(equipmentDiffCtrl);
        }

        /// <summary>
        /// 保存记录按钮单击事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void BtnSaveRecord_Click(object sender, RoutedEventArgs e)
        {
            _bll.SetCurrentCycleTime(Convert.ToDouble(numberCtTime.Value));
            RefreshLineName();
        }

        /// <summary>
        /// 时间单位下拉菜单变更事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void CmbTimeUnit_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBoxItem item = cmbTimeUnit.SelectedItem as ComboBoxItem;
            if (item == null)
            {
                return;
            }
            string timeUnit = item.Content as string;
            if (!string.IsNullOrWhiteSpace(timeUnit))
            {
                _bll.SetCurrentTimeUnit(timeUnit);
                RefreshCtTime();
            }
        }

        /// <summary>
        /// 设备下拉菜单选定变更事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void CmbMachine_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string currentMacine = cmbMachine.SelectedItem as string;
            if (!string.IsNullOrWhiteSpace(currentMacine))
            {
                _bll.SetCurrentMachine(currentMacine);
                RefreshCtTime();
            }
        }

        /// <summary>
        /// 添加设备按钮单击事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void BtnAddMachine_Click(object sender, RoutedEventArgs e)
        {
            string machine = txtAddMachine.Text;
            if (!string.IsNullOrWhiteSpace(machine))
            {
                _bll.AddMachine(machine);
                RefreshMachine();
            }
        }

        /// <summary>
        /// 工站下拉菜单选定变更事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void CmbWorkStation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string currentWorkStation = cmbWorkStation.SelectedItem as string;
            if (!string.IsNullOrWhiteSpace(currentWorkStation))
            {
                _bll.SetCurrentWorkStation(currentWorkStation);
                RefreshMachine();
            }
        }
        /// <summary>
        /// 添加工站按钮单击事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void BtnAddWorkStation_Click(object sender, RoutedEventArgs e)
        {
            string txt = txtAddWorkStation.Text;
            if (!string.IsNullOrWhiteSpace(txt))
            {
                _bll.AddWorkStation(txt);
                RefreshWorkStation();
            }
        }

        /// <summary>
        /// 版本下拉菜单变化选定变化事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void CmbVersion_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int? currentVersion = cmbVersion.SelectedItem as int?;
            if (currentVersion != null)
            {
                _bll.SetCurrentVersion(currentVersion.Value);
                RefreshWorkStation();
            }
        }

        /// <summary>
        /// 版本添加按钮单击事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void BtnAddVersion_Click(object sender, RoutedEventArgs e)
        {
            int? currentVersion = cmbVersion.SelectedItem as int?;
            if (currentVersion == null)
            {
                currentVersion = 1;
            }
            else
            {
                currentVersion = currentVersion.Value + 1;
            }
            _bll.AddVersion(currentVersion.Value);
            RefreshVersion();
        }

        /// <summary>
        /// 产线下拉菜单变化选定变化事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void CmbLine_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string currentLineName = cmbLine.SelectedItem as string;
            if (!string.IsNullOrWhiteSpace(currentLineName))
            {
                _bll.SetCurrentLineName(currentLineName);
            }
            RefreshVersion();
        }

        /// <summary>
        /// 添加产线单击事件
        /// </summary>
        /// <param name="sender">事件对象</param>
        /// <param name="e">事件参数</param>
        private void BtnAddLine_Click(object sender, RoutedEventArgs e)
        {
            string txt = txtAddLineName.Text;
            if (!string.IsNullOrWhiteSpace(txt))
            {
                _bll.AddLineName(txt);
                RefreshLineName();
            }
        }

        /// <summary>
        /// 刷新基础数据
        /// </summary>
        private void RefreshBaseData()
        {
            BalanceDataCtrl controlCtrl = new BalanceDataCtrl("线平衡数据", _bll.AllItem);
            if (lineBalanceDataContainer.Children.Count > 0)
            {
                lineBalanceDataContainer.Children.Clear();
            }
            lineBalanceDataContainer.Children.Add(controlCtrl);
        }

        /// <summary>
        /// 刷新CT时间
        /// </summary>
        private void RefreshCtTime()
        {
            double ctTime = _bll.CtTime;
            numberCtTime.Dispatcher.Invoke(() =>
            {
                if (ctTime >= 0)
                {
                    numberCtTime.Value = Convert.ToDecimal(ctTime);
                }
            });
            txtLineBalanceTag.Visibility = Visibility.Hidden;
            txtLineBalanceValue.Visibility = Visibility.Hidden;
            RefreshBaseData();
        }

        /// <summary>
        /// 刷新设备
        /// </summary>
        private void RefreshMachine()
        {
            List<string> machines = _bll.AllMachine;
            cmbMachine.Dispatcher.Invoke(() =>
            {
                cmbMachine.Items.Clear();
                if (machines != null && machines.Count > 0)
                {
                    foreach (string machine in machines)
                    {
                        cmbMachine.Items.Add(machine);
                    }
                    cmbMachine.SelectedIndex = machines.Count - 1;
                }
            });
        }

        /// <summary>
        /// 刷新工站
        /// </summary>
        private void RefreshWorkStation()
        {
            List<string> workStations = _bll.AllWorkStation;
            cmbWorkStation.Dispatcher.Invoke(() =>
            {
                cmbWorkStation.Items.Clear();
                if (workStations != null && workStations.Count > 0)
                {
                    foreach (string workStation in workStations)
                    {
                        cmbWorkStation.Items.Add(workStation);
                    }
                    cmbWorkStation.SelectedIndex = workStations.Count - 1;
                }
            });
        }

        /// <summary>
        /// 刷新版本
        /// </summary>
        private void RefreshVersion()
        {
            List<int> versions = _bll.AllVersion;
            cmbVersion.Dispatcher.Invoke(() =>
            {
                cmbVersion.Items.Clear();
                if (versions != null && versions.Count > 0)
                {
                    foreach (int version in versions)
                    {
                        cmbVersion.Items.Add(version);
                    }
                    cmbVersion.SelectedIndex = versions.Count - 1;
                }
            });

        }

        /// <summary>
        /// 刷新产线名称
        /// </summary>
        private void RefreshLineName()
        {
            List<string> lineNames = _bll.AllLineName;
            cmbLine.Dispatcher.Invoke(() =>
            {
                cmbLine.Items.Clear();
                if (lineNames != null && lineNames.Count > 0)
                {
                    foreach (string lineName in lineNames)
                    {
                        cmbLine.Items.Add(lineName);
                    }
                    cmbLine.SelectedIndex = lineNames.Count - 1;
                }
            });
        }
        /// <summary>
        /// 线平衡业务
        /// </summary>
        private LineBalanceBll _bll = new LineBalanceBll();
    }
}
